<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
	<!-- 去掉本服务器的头信息 -->
    <meta name="referrer" content="no-referrer" >
    <title>Document</title>
    <link rel="stylesheet" href="../css/details.css">
    <script src="../js/jquery-1.10.1.min.js"></script>
    <script src="../js/cookie.js"></script>
    <script src="../js/api_2.js"></script>
    <!-- <script src="../js/details.js"></script> -->
</head>

<body>
    <div class="header">
        <ul class="header_left">
            <li><span class="iconfont icon-xingxing"></span><a href="javascript:;" class="Collection">收藏鲜花网(hua.com)</a></li>
            <li><span class="iconfont icon-weixin"></span><a href="">关注微信</a></li>
            <li><span class="iconfont icon-shoujichongzhi"></span><a href="https://www.hua.com/mobile/">花礼网app</a></li>
        </ul>
        <ul class="header_right">
            <li class="tips">
                <a href="./login.html">你好,请登录</a>
                <a href="./register.html">注册</a>
            </li>
            <li>|</li>
            <li><a href="https://www.hua.com/help/ordercx/">订单查询</a></li>
            <li>|</li>
            <li><a href="./login.html">我的花礼</a></li>
            <li>|</li>
            <li class="customer_service">
                <a href="https://www.hua.com/help/">客户服务</a>
                <div class="dropdown-menu dropdown-service">
                    <a href="https://www.hua.com/member/payment/balancefill" target="_blank">在线付款</a>
                    <a href="https://www.hua.com/help/" target="_blank">帮助中心</a>
                    <a href="https://www.hua.com/help/afterservice.htm" target="_blank">售后服务</a>
                    <a href="https://www.hua.com/help/sendRange.htm" target="_blank">配送范围</a>
                    <a href="https://www.hua.com/chat/" target="_blank">留言反馈</a>
                </div>
            </li>
            <li>|</li>
            <li class="shopping_cart">
                <a href=""><span class="iconfont icon-qicheqianlian-"></span>购物车</a>
                <div class="dropdown-menu dropdown-cart" id="CartInfo">
                    <div class="empty">您的购物车中没有商品，<a href="/">先去选购吧</a>！</div>
                </div>
            </li>
            <li>|</li>
            <li><a href="">中国领先鲜花速递服务</a></li>
        </ul>
    </div>
    
    <div class="preview">
        <div class="left">
            <!-- <div class="bigImg">
                <div class="shadow"></div>
                <img src="../images/sp1.jpg" alt="" class="shadowImg">
            </div>
            <div class="bigImgShow">
                <img src="../images/sp1.jpg" alt="" class="ImgShow">
            </div> -->
            <ul class="switchList">
                <!-- <li class="active"><a href=""><img src="../images/sp11.jpg" alt=""></a></li>
                <li><a href=""><img src="../images/sp12.jpg" alt=""></a></li>
                <li><a href=""><img src="../images/sp13.jpg" alt=""></a></li>
                <li><a href=""><img src="../images/sp14.jpg" alt=""></a></li> -->
            </ul>
        </div>
        <div class="right">
            <!--<h2>Apple iPhone 11 (A2223) 128GB 黑色 移动联通电信4G手机 双卡双待</h2>
            <div>
                京 东 价:￥ <span class="price" value="4999.00">4999.00</span> 降价通知
            </div>
            <div class="buyNum">
                <span class="reduce" style="cursor: pointer;">-</span>
                <input type="number" value="1">
                <span class="add" style="cursor: pointer;">+</span>
            </div>
            <div class="provinces">
                <span>配送至：</span>
                <select class="province">
                    <option value="">请选择省份</option>
                </select>
                <select class="city">
                    <option value="">请选择市区</option>
                </select>
                <select class="town">
                    <option value="">请选择县区</option>
                </select>
            </div>
            <button class="addToCar">
                加入购物车
            </button>
        </div>-->
    </div>
    <!-- <div class="detail">

    </div> -->
</body>
<script>
    $(function () {
	if (getCookie("lgc")) {
            $(".tips").html("欢迎您," + getCookie("lgc") + "<button onclick='exit()'>退出</button>");
        }
	
    
    id = getSearchString('gid');
    //console.log(id);


    loadGoods();
    function loadGoods() {
        searchGoodsById({ id }).then(function (result) {
                // var { status, detail, list, maxPage } = result;
                console.log(result);
                var [list] = result;
                console.log(list);
                // console.log(result);
                var html = "";
                var html1 = "";
				var listHTML = "";
                // list.forEach(({ id, goodsId, goodsName, goodsImg, goodsPrice }) => {
				
                var { id, goodsId, goodsName, goodsPrice, bigPicList, smallPicList  } = list;
				console.log(smallPicList,smallPicList.length);
                html += ` <h2>${goodsName}</h2>
        <div>
            售 价:￥ <span class="price">${goodsPrice}</span> 降价通知
        </div>
        <div class="buyNum">
            <span class="reduce">-</span>
            <input type="number" value="1" class="count-input">
            <span class="add">+</span>
        </div>
        <div class="provinces">
            <span>配送至：</span>
            <select class="province">
                <option value="">请选择省份</option>
            </select>
            <select class="city">
                <option value="">请选择市区</option>
            </select>
            <select class="town">
                <option value="">请选择县区</option>
            </select>
        </div>
        <button class="addToCar">
            加入购物车
        </button> `
                html1 += `<div class="bigImg">
            <div class="shadow"></div>
            <img src="${bigPicList[0]}" alt="" class="shadowImg">
        </div>
		<ul class="switchList">
                           
        </ul>
        <div class="bigImgShow">
            <img src="${bigPicList[0]}" alt="" class="ImgShow">
        </div>`
		var len = smallPicList.length;
		var arr = smallPicList.split(",");
		console.log(arr)
                for (var i = 0; i < (len > 4 ? 4 : len); i++) {
                    var img = arr[i];
                    listHTML += `<li><img src="${img}" bigUrl="${img}" alt=""></li>`
                }
				$(".left").html(html1);
                $(".right").html(html);
                $(".switchList").html(listHTML);
                $(".switchList li").eq(0).addClass("active");
				
        $(document).on("click", ".switchList li", function () {
        $(this).addClass("active").siblings().removeClass("active");
        var url = $(this).find("img").attr("bigUrl");
        $(".ImgShow,.shadowImg").prop("src", url);
    })



            //商品增加/减少
            var p = $(".price").text();
            $(document).on("click", ".add", function () {
                var val = $(this).prev().val();
                // console.log($(this).prev().val());
                val++;
                $(this).prev().val(val);
                // console.log($(".price").text());
                $(".price").text((val * p * 1).toFixed(2));
            })

            $(document).on("click", ".reduce", function () {
                var val = $(this).next().val();
                $(".price").text((val * p * 1).toFixed(2));
                if (val <= 1) {
                    $(this).off("click");
                } else {
                    val--;
                    $(this).next().val(val);
                    $(".price").text((val * p * 1).toFixed(2));
                }
            })

            $(document).on("blur", ".number", function () {
                var val = $(".number").val();
                console.log($(".number").val());
                $(".price").text((val * p * 1).toFixed(2));
            })

            //省市区三级联动
            var province = document.getElementsByClassName("province")[0];
    var city = document.getElementsByClassName("city")[0];
    var town = document.getElementsByClassName("town")[0];
    var xhr = new XMLHttpRequest();

    xhr.open("get", "../data/proData.json", true);

    xhr.send();

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var result = JSON.parse(xhr.responseText);
            // console.log(result);
            var { list: proList } = result;
            var html = `<option value="">请选择省份</option>`;
            proList.forEach(function (item) {
                var { city_id, name } = item;
                // <option value="">请选择省份</option>
                html += `<option value="${city_id}">${name}</option>`;
            })
            province.innerHTML = html;
            province.onchange = function () {
                var cityId = this.value;
                if (cityId) {
                    // console.log(cityId, proList);
                    var arr = proList.filter(function (item) {
                        return cityId == item.city_id;
                    });
                    var thisPro = arr[0];
                    // console.log(thisPro);
                    var { list: cityList } = thisPro;
                    var html = '<option value="">请选择市区</option>';
                    cityList.forEach(function (item) {
                        var { city_id, name } = item;
                        html += `<option value="${city_id}">${name}</option>`;
                    })
                    city.innerHTML = html;
                    town.innerHTML = `<option value="">请选择县区</option>`;
                    // town.style.display = "none";


                    city.onchange = function () {
                        var cityId = this.value;
                        if (cityId) {
                            // console.log(cityId, proList);
                            var arr = cityList.filter(function (item) {
                                return cityId == item.city_id;
                            });
                            var thisCity = arr[0];
                            // console.log(thisCity);
                            var { list: townList } = thisCity;
                            if (townList) {
                                town.style.display = "inline-block";
                                console.log(townList);
                                var html = '<option value="">请选择县区</option>';
                                townList.forEach(function (item) {
                                    var { city_id, name } = item;
                                    html += `<option value="${city_id}">${name}</option>`;
                                })
                                town.innerHTML = html;
                            } else {
                                town.style.display = "none";
                            }
                        } else {
                            town.innerHTML = '<option value="">请选择县区</option>';
                        }
                    }
                } else {
                    city.innerHTML = '<option value="">请选择市区</option>';
                    town.innerHTML = '<option value="">请选择县区</option>';
                }
            }
        }
    }

            //放大镜
			var bigImg = document.querySelector(".bigImg");
			var bigImgShow = document.querySelector(".bigImgShow");
			var shadow = document.querySelector(".shadow");
			var shadowImg = document.querySelector(".shadowImg");
			var ImgShow = document.querySelector(".ImgShow");
			
            bigImg.onmouseenter = function (e) {
                bigImgShow.style.display = "block";
                shadow.style.display = "block";
            }

           bigImg.onmouseleave = function (e) {
                bigImgShow.style.display = "none";
                shadow.style.display = "none";
            }

            bigImg.onmousemove = function (e) {
                var e = e || window.event;
                var scale = ImgShow.clientHeight / shadowImg.clientHeight;
                var maxLeft = bigImg.clientWidth - shadow.clientWidth + 30;
                var maxTop = bigImg.clientHeight - shadow.clientHeight + 74;

                var x = e.pageX - bigImg.offsetLeft - shadow.clientWidth / 2;
                var y = e.pageY - bigImg.offsetTop - shadow.clientHeight / 2;

                if (x < 30) x = 30;
                if (x >= maxLeft) x = maxLeft;
                if (y < 74) y = 74;
                if (y >= maxTop) y = maxTop;

                shadow.style.left = x + "px";
                shadow.style.top = y + "px";

                ImgShow.style.left = -scale * x + "px";
                ImgShow.style.top = -scale * y + "px";
				//console.log(x,y);
            }
        }).catch(err => {
            // tbody.innerHTML = `<tr><td colspan="9">暂无数据</td></tr>`;
            throw err;
        });
    }

})

$(document).on("click", ".addToCar", async function () {
        console.log("点击加入购物车")
        var user = getCookie("lgc");  // 当前登录的用户
        console.log(user);
        if (user) { 
		var buyNum = $(".buyNum .count-input").val();
            console.log(buyNum);
			var id = getSearchString('gid');
			console.log(id);
            // addShoppingCar({ user, goodsId: id, buyNum }).then().catch()

            var result = await addShoppingCar({ user, goodsId: id, buyNum });
            console.log(result);
            var { status } = result;
            if (status) {
                if (confirm("购买成功,是否进入购物车?")) {
                    location.href = "./shoppingCar.html"
                }
            } else {
                alert("系统繁忙,请稍后...");
            }
        } else { 
            location.href = "./login.html?returnUrl=" + encodeURIComponent(location.href);
        }
    })
	
	$(document).on("click", ".shopping_cart", async function () {
        console.log("点击加入购物车")
        var user = getCookie("lgc");  // 当前登录的用户
        console.log(user);
        if (user) {
            location.href= "./shoppingCar.html";
        }else{
            alert("请登录后查看")
        }
    })

function exit() {
        delCookie("lgc");
        location.reload();
    }
	
	function getSearchString(key) {
        var str = window.location.search;
        str = str.substring(1, str.length); // 获取URL中?之后的字符（去掉第一位的问号）
        // 以&分隔字符串，获得类似name=xiaoli这样的元素数组
        var arr = str.split("&");
        var obj = new Object();
        // 将每一个数组元素以=分隔并赋给obj对象
        for (var i = 0; i < arr.length; i++) {
            var tmp_arr = arr[i].split("=");
            obj[decodeURIComponent(tmp_arr[0])] = decodeURIComponent(tmp_arr[1]);
        }
        return obj[key];
    }
</script>

</html>